package com.echo.controller; /***********************************************************
 * @Description : 对外REST接口
 * @email       : echo@gmail.com
 ***********************************************************/

import com.echo.context.WisUserIdContext;
import com.echo.dto.RegisterDTO;
import com.echo.dto.WisUserDTO;
import com.echo.entity.WisUser;
import com.echo.enumeration.ResultEnum;
import com.echo.qo.LoginQo;
import com.echo.service.IWisUserService;

import com.echo.result.ResultVO;
import com.echo.vo.WisUserInfoVo;
import com.echo.vo.WisUserVo;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

@RestController
@Tag(name = "WAiUser APIs")
@RequestMapping("/api/wisuser")
public class WisUserController {

    @Autowired
    private IWisUserService userService;
    private final RedisTemplate<String, String> redisTemplate;

    public WisUserController(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @PostMapping("/register")
    @Operation(summary = "注册")
    public ResultVO<WisUser> register(@RequestBody RegisterDTO registerDTO) {
        // 提取邮箱和验证码
        String email = registerDTO.getEmail();
        String inputCaptcha = registerDTO.getCaptcha();

        // 从 Redis 获取验证码
        String storedCaptcha = redisTemplate.opsForValue().get("captcha:" + email);

        // 验证码校验
        if (storedCaptcha == null || !storedCaptcha.equals(inputCaptcha)) {
            return new ResultVO<>(ResultEnum.REGISTER_FAILED.getCode(), "验证码错误或已过期", null);
        }

        // 继续注册逻辑
        ResultVO<WisUser> resultVO;
        WisUser wisUser = userService.register(registerDTO);
        if (wisUser != null) {
            // 注册成功
            resultVO = new ResultVO<>(ResultEnum.REGISTER_SUCCESS.getCode(), ResultEnum.REGISTER_SUCCESS.getMessage(), wisUser);

            // 删除 Redis 中的验证码
            redisTemplate.delete("captcha:" + email);
        } else {
            resultVO = new ResultVO<>(ResultEnum.REGISTER_FAILED.getCode(), ResultEnum.REGISTER_FAILED.getMessage(), null);
        }
        return resultVO;
    }


    @PostMapping("/login")
    @Operation(summary ="根据用户名或邮箱登录,登录成功返回token")
    ResultVO<String> login(@RequestBody LoginQo loginQo) { // 这里不用手机号是因为手机号和用户名难以进行格式区分，而用户名和
        // 用户登录
        ResultVO<String> resultVO;
        String token = userService.login(loginQo);
        if (token != null) {
            // 登录成功
            resultVO = new ResultVO<>(ResultEnum.LOGIN_SUCCESS.getCode(), ResultEnum.LOGIN_SUCCESS.getMessage(), token);
        } else {
            // 登录失败
            resultVO = new ResultVO<>(ResultEnum.LOGIN_FAILED.getCode(), ResultEnum.LOGIN_FAILED.getMessage(), null);
        }
        System.out.println(resultVO);
        return resultVO;
    }

    @GetMapping("/user-info")
    @Operation(summary ="获取用户信息")
    ResultVO<WisUserVo> getUserInfo(HttpServletRequest request) {
        String userId = (String) request.getAttribute("user_id");
        System.out.println(userId);
        WisUserVo wisUserVo = userService.getUserInfo(userId);
        return new ResultVO<>(ResultEnum.GET_INFO_SUCCESS.getCode(), ResultEnum.GET_INFO_SUCCESS.getMessage(), wisUserVo);
    }
    @PostMapping("/changerUserInfo")
    @Operation(summary = "修改用户信息")
    public ResultVO changeUserInfo(@RequestBody WisUserDTO userDTO) {
        String userId = WisUserIdContext.getUserIdContext();
        if (userId == null) {
            return new ResultVO<>(-1, "未登录", null);
        }
        // 保存用户信息到数据库
        boolean result = userService.changerUserInfo(userDTO,userId);

        if (result) {
            return ResultVO.success(null);
        } else {
            return ResultVO.error(500,"修改失败");
        }
    }

    @GetMapping("/info")
    @Operation(summary ="获取用户的详细信息，包括个人信息页面和操作权限")
    ResultVO<WisUserInfoVo> getInfo(HttpServletRequest request) {
        System.out.println("进入/user/info的获取用户信息的接口");
        String userId = (String) request.getAttribute("user_id");
        WisUserInfoVo wisUserInfoVo = userService.getInfo(userId);
        return new ResultVO<>(ResultEnum.GET_INFO_SUCCESS.getCode(), ResultEnum.GET_INFO_SUCCESS.getMessage(), wisUserInfoVo);
    }

    @GetMapping("/test")
    @Operation(summary ="测试接口")
    String test(HttpServletRequest request) {
        // 下面这两个属性都是登录拦截器从token中解析地，当用户名不对或者token过期时是走不到接口内的
        String userId = (String) request.getAttribute("user_id");
        String username = (String) request.getAttribute("username");
        System.out.println("用户id：" + userId);
        System.out.println("用户名：" + username);
        return "用户id：" + userId + "\n用户名：" + username;
    }
}
